package com.example.onlineanswer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.onlineanswer.common.util.JwtUtil;
import com.example.onlineanswer.mapper.SysUserMapper;
import com.example.onlineanswer.model.entity.SysUser;
import com.example.onlineanswer.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 用户服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public SysUser getByUsername(String username) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        return getOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean register(SysUser user) {
        // 检查用户名是否已存在
        SysUser existUser = getByUsername(user.getUsername());
        if (existUser != null) {
            return false;
        }
        
        // 设置默认值
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setStatus(1); // 激活状态
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        return save(user);
    }

    @Override
    public String login(String username, String password) {
        // 查询用户
        SysUser user = getByUsername(username);
        if (user == null) {
            return null;
        }
        
        // 检查密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return null;
        }
        
        // 检查用户状态
        if (user.getStatus() != 1) {
            return null;
        }
        
        // 生成JWT令牌
        return jwtUtil.generateToken(user.getUsername(), user.getRoleCode(), user.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserInfo(SysUser user) {
        user.setUpdateTime(LocalDateTime.now());
        // 不更新敏感字段
        user.setPassword(null);
        return updateById(user);
    }
} 